package com.dailyblue.java.project.bookstore.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dailyblue.java.project.bookstore.bean.Book;
import com.dailyblue.java.project.bookstore.mapper.BookMapper;
import com.dailyblue.java.project.bookstore.service.BookService;
import com.dailyblue.java.project.bookstore.util.JsonResult;
import com.dailyblue.java.project.bookstore.util.ResultTool;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class BookServiceImpl extends ServiceImpl<BookMapper, Book> implements BookService {

    @Cacheable(cacheNames = "findNewBook", key = "#num")
    public JsonResult findNewBook(int num) {
        PageHelper.startPage(1, num);
        QueryWrapper<Book> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("create_time");
        List<Book> books = list(wrapper);
        return ResultTool.success(books);
    }

    @Cacheable(cacheNames = "findBookByItem", key = "#itemId+'_'+#page")
    public JsonResult findBookByItem(String itemId, int page) {
        PageHelper.startPage(page, 10);
        QueryWrapper<Book> wrapper = new QueryWrapper<>();
        wrapper.eq("category_id", itemId);
        wrapper.eq("state", "1");
        List<Book> books = list(wrapper);
        PageInfo<Book> pageInfo = new PageInfo<>(books);
        return ResultTool.success(pageInfo);
    }

    @Cacheable(cacheNames = "findSearchByBookNameAndItem", key = "#itemId+'_'+#page+'_'+#bookName")
    public JsonResult findSearchByBookNameAndItem(String itemId, int page, String bookName) {
        PageHelper.startPage(page, 10);
        QueryWrapper<Book> wrapper = new QueryWrapper<>();
        if (itemId != null) {
            wrapper.eq("category_id", itemId);
        }
        wrapper.eq("state", "1");
        wrapper.like("name", bookName).or().like("author", bookName);
        List<Book> books = list(wrapper);
        PageInfo<Book> pageInfo = new PageInfo<>(books);
        return ResultTool.success(pageInfo);
    }
}
